package com.fulu.jvm;


/**
 * 指令重排序测试
 * 1. 定义一个类，包含三个属性
 * 2. 循环开线程实例化，并赋值
 * 3. 开线程读取实体属性，观察是否符合预期
 */
public class InstructionReorder {

    public static void main(String[] args) {

        for (int i = 0; i < 1000000; i++) {
            final ReorderMe reorderMe = new ReorderMe();
            new Thread(() -> {
                reorderMe.a = 1;
                reorderMe.b = 2;
                reorderMe.c = reorderMe.a + reorderMe.b;
            }).start();

            new Thread(() -> {
                int tmpa = reorderMe.a, tmpb = reorderMe.b, tmpc = reorderMe.c;
                if(tmpb == 2 && tmpa == 0) {
                    System.out.println("Instruction Reordering: a = " + tmpa + ", b = " + tmpb + ", c = " + tmpc);
                }
                if(tmpc > 0 && tmpa == 0) {
                    System.out.println("Instruction Reordering: a = " + tmpa + ", b = " + tmpb + ", c = " + tmpc);
                }
                if(tmpc > 0 && tmpb == 0) {
                    System.out.println("Instruction Reordering: a = " + tmpa + ", b = " + tmpb + ", c = " + tmpc);
                }
            }).start();
        }
    }

    static class ReorderMe {
        int a = 0, b = 0, c = 0;

    }

}
